package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto 前端传递的所有参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        try {
            // 1. 校验老人是否已入住
            LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
            queryWrapper.eq(Elder::getStatus, 1);
            Elder elder = elderMapper.selectOne(queryWrapper);
            if (ObjectUtils.isNotEmpty(elder)) {
                throw new BaseException("该老人已入住");
            }
            // 2. 更新床位状态为已入住
            Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            // 3. 新增或更新老人
            elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);
            // 4. 新增签约办理
            insertContract(dto, elder);
            // 5. 新增入住信息
            CheckIn checkIn = insertCheckIn(elder, dto);
            // 6. 新增入住配置
            insertCheckInConfig(checkIn, dto);
        } catch (BaseException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 新增入住配置
     *
     * @param checkIn 入住信息
     * @param dto     前端传递的参数
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder 老人信息
     * @param dto   前端传递的参数
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);

        // 保存老人家属信息
        // 老人家属信息只用于数据展示 , 转换为JSON字符串 , 并存入CheckIn表的remark字段中.
        // 对象转JSON
        String jsonString = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(jsonString);
        // JSON转对象
        List<ElderFamilyDto> elderFamilyDtoList = JSON.parseArray(jsonString, ElderFamilyDto.class);
        System.out.println(elderFamilyDtoList);


        checkInMapper.insert(checkIn);

        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param dto   前端传递的参数
     * @param elder 老人信息
     */
    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        // 从入住配置中获取开启和结束的时间(入住的开始和结束时间)
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        // 判断合同状态
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        // 保存
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     *
     * @param checkInElderDto 前端传递的参数
     * @param bed             床位信息
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder e = new Elder();
        BeanUtils.copyProperties(checkInElderDto, e);
        e.setBedId(bed.getId());
        e.setBedNumber(bed.getBedNumber());
        e.setStatus(1);

        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 0);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(elder)) {
            // 新增
            elderMapper.insert(e);
        } else {
            // 更新
            e.setId(elder.getId());
            elderMapper.updateById(e);
        }
        return e;
    }

    /**
     * 查询入住详情
     *
     * @param id 入住ID
     * @return 详情
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 1. 查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Long elderId = checkIn.getElderId();
        LocalDateTime startDate = checkIn.getStartDate();
        LocalDateTime endDate = checkIn.getEndDate();
        String bedNumber = checkIn.getBedNumber();

        // 2. 查询老人信息
        Elder elder = elderMapper.selectElderById(elderId);
        if (ObjectUtils.isNotEmpty(elder)) {
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder, checkInElderVo);
            checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
            checkInDetailVo.setCheckInElderVo(checkInElderVo);
        }

        // 3. 查询合同信息
        LambdaQueryWrapper<Contract> queryContractWrapper = new LambdaQueryWrapper<>();
        queryContractWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(queryContractWrapper);
        checkInDetailVo.setContract(contract);

        // 4. 获取入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryCheckInConfigWrapper = new LambdaQueryWrapper<>();
        queryCheckInConfigWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryCheckInConfigWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(bedNumber);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        // 5. 转换家属列表
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        // 6. 整合数据返回
        return checkInDetailVo;
    }
}